package com.diancan.modules.user.user;

import com.alibaba.fastjson2.JSONObject;
import com.diancan.common.Result;
import com.diancan.domain.User;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("user")
public class UserController {
    @Value("${wechat.appid}")
    String appid;
    @Value("${wechat.secret}")
    String secret;
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    // 增删改查
    @PostMapping("insert")
    public Result insertUser(@RequestBody User user) {
        System.out.println(user);
        return Result.buildSuccessResult(userService.save(user));
    }

    @GetMapping("delete")
    public Result deleteUserById(String id) {
        return Result.buildSuccessResult(userService.removeById(id));
    }

    @PostMapping("update")
    public Result updateUser(@RequestBody User user) {
        return Result.buildSuccessResult(userService.updateById(user));
    }

    @GetMapping("selectById")
    public Result selectUserById(String id) {
        return Result.buildSuccessResult(userService.getById(id));
    }

    @GetMapping("selectAll")
    public Result selectAllUser() {
        return Result.buildSuccessResult(userService.selectAllUser());
    }

    // 注册
    @PostMapping("register")
    public Result register(@RequestBody User user) {
        try {
            return Result.buildSuccessResult(userService.save(user));
        } catch (Exception e) {
            return Result.buildFailureResult("账号重复");
        }
    }

    // 获取openid
    @GetMapping("applets")
    public Result applets(String code) throws IOException {
        System.out.println(code);

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid +
                "&secret=" + secret +
                "&js_code=" + code +
                "&grant_type=authorization_code";

        // 创建httpClient实例对象
        HttpClient httpClient = new HttpClient();
        // 设置httpClient连接主机服务器超时时间：15000毫秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        // 创建GET请求方法实例对象
        GetMethod getMethod = new GetMethod(url);
        // 设置get请求超时时间
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
        getMethod.addRequestHeader("Content-Type", "application/json");

        httpClient.executeMethod(getMethod);
        String result = getMethod.getResponseBodyAsString();
        JSONObject jsonObject = JSONObject.parseObject(result);

        return Result.buildSuccessResult(jsonObject);
    }
}
